using System;
using System.ComponentModel.Composition;
using System.Text.RegularExpressions;
using SMSManager.Commn.Interfaces;
using SMSManager.Data.Properties;

namespace SMSManager.Data
{
	[Export(typeof (IUser))]
	[PartCreationPolicy(CreationPolicy.NonShared)]
	public class User : NotifyPropertyChangedBase, IUser
	{
		private bool _isAutoLogin;
		private bool _isRemember;

		public User()
		{
			Id = string.Empty;
			Password = string.Empty;
			_isRemember = false;
			_isAutoLogin = false;
		}

		public override bool Equals(object obj)
		{
			if (ReferenceEquals(null, obj)) return false;
			if (ReferenceEquals(this, obj)) return true;
			if (obj.GetType() != typeof (User)) return false;
			return Equals((User) obj);
		}

		public override int GetHashCode()
		{
			unchecked
			{
				int result = (Id != null ? Id.GetHashCode() : 0);
				result = (result*397) ^ (Password != null ? Password.GetHashCode() : 0);
				return result;
			}
		}

		public bool Equals(User other)
		{
			if (ReferenceEquals(null, other)) return false;
			if (ReferenceEquals(this, other)) return true;
			return other._isAutoLogin.Equals(_isAutoLogin)
			       && other._isRemember.Equals(_isRemember)
			       && Equals(other.Id, Id)
			       && Equals(other.Password, Password);
		}

		public string this[string propertyName]
		{
			get
			{
				bool valid = false;
				switch (propertyName)
				{
					case "Id":
						valid = Regex.IsMatch(Id, Resources.IdRegex);
						if (!valid) return Resources.IdInvalidMessage;
						break;
					case "Password":
						valid = Regex.IsMatch(Password, Resources.PasswordRegex);
						if (!valid) return Resources.PasswordInvalidMessage;
						break;
				}
				return null;
			}
		}

		public string Error
		{
			get { throw new NotSupportedException(); }
		}

		public string Id { get; set; }

		public bool IsAutoLogin
		{
			get { return _isAutoLogin; }
			set
			{
				_isAutoLogin = value;
				if (!_isRemember && value)
				{
					_isRemember = true;
					this.OnPropertyChanged(x => x.IsRemember);
				}
			}
		}

		public bool IsRemember
		{
			get { return _isRemember; }
			set
			{
				_isRemember = value;
				if (_isAutoLogin && !value)
				{
					_isAutoLogin = false;
					this.OnPropertyChanged(x => x.IsAutoLogin);
				}
			}
		}

		public string Password { get; set; }
	}
}